﻿/************************************************************************************
 *      Copyright (C) 2019 All Rights Reserved
 *      File:
 *				WebApiErrorHandleAttribute.cs
 *      Description:
 *		    webApi异常总的处理类
 *      Author:
 *			 Dawen Yang
 *				
 *	
 *      Create DateTime:
 *				2019年05月29日
 *      History:
 ***********************************************************************************/

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Web;
using System.Web.Http.Filters;
using ELearning.BLL;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Oprator;
using NLog;

namespace ELearning.API.HandleAttribute
{
    /// <summary>
    /// 接口异常捕捉过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public class ApiErrorHandleAttribute : ExceptionFilterAttribute
    {
        protected static ESysUserService UserService = new ESysUserService();
        private static Logger logger = LogManager.GetCurrentClassLogger(); //初始化日志类
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);
            actionExecutedContext.Response = GetResponse(actionExecutedContext);
        }

        /// <summary>
        /// 捕捉异常后响应方法
        /// </summary>
        private HttpResponseMessage GetResponse(HttpActionExecutedContext actionExecutedContext)
        {
            string requesthost = actionExecutedContext.ActionContext.Request.RequestUri.ToString();
            string Method = actionExecutedContext.ActionContext.Request.Method.ToString();
            string controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
            string action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
            string UserIdentity = null;
            String IP = HttpContext.Current.Request.UserHostAddress;
            string host = Dns.GetHostName();

            WriteHelper.WriteFile($"GetResponse---------{actionExecutedContext.Exception.ToJson()}");
            WriteHelper.WriteFile(actionExecutedContext.Exception);
            //String ua = Request.getHeader("User-Agent");
            string AppUser = null;
            var currentUserModel = OperatorProvider.Provider.GetCurrent();
            if (currentUserModel == null)
            {
                var email = ClaimsPrincipal.Current.Identity.Name;//配合azure认证使用，也可以改成自己认证，
                var loginName = email.Split('@')[0];
                var user = UserService.GetUserByLoginName(loginName);
                if (user != null)
                {
                    AppUser = user.UserName;
                    UserIdentity = email;
                    //currentUserModel = new OperatorModel
                    //{
                    //    Email = user.Email,
                    //    HeadPhoto = user.HeadPhoto,
                    //    LoginName = user.LoginName,
                    //    MobilePhone = user.MobilePhone,
                    //    Position = user.Position,
                    //    Remark = user.Remark,
                    //    UserId = user.UserID,    
                    //    UserName = user.UserName,
                    //    UserType = user.UserType
                    //};
                    //OperatorProvider.Provider.AddCurrent(currentUserModel);
                }
            }

            LogEventInfo lei = new LogEventInfo();
            lei.Properties.Add("RequestIP",IP);
            lei.Properties.Add("RequestUrl", requesthost);
            lei.Properties.Add("Method",Method);
            lei.Properties.Add("Controller", controller);
            lei.Properties.Add("Action",action);
            lei.Properties.Add("AppName", "HsLearn");
            lei.Properties.Add("Message", actionExecutedContext.Exception.Message);
            lei.Properties.Add("ExceptionMessage", actionExecutedContext.Exception);
            lei.Properties.Add("ExceptionStackTrace", actionExecutedContext.Exception);
            lei.Properties.Add("AppUser", AppUser);
            lei.Properties.Add("UserIdentity", UserIdentity);
            lei.Properties.Add("MachineUser", "MachineUser");
            lei.Properties.Add("Priority", 9);
            lei.Properties.Add("LogLevel", "Error");
            lei.Level = LogLevel.Error;
            logger.Error(lei);
            var response = actionExecutedContext.Exception.LogAndResponse<int>();
            return JsonHelper.ToHttpResponseMessage(response);
        }

        private string GetExceptionMessage(HttpActionExecutedContext actionExecutedContext)
        {
            var session = System.Web.HttpContext.Current.Session;
            var request = System.Web.HttpContext.Current.Request;
            var keys = request.Form.AllKeys;
            var guid = Guid.NewGuid().ToString();
            var task = actionExecutedContext.ActionContext.Request.Content.ReadAsStreamAsync();
            var content = string.Empty;
            using (var sm = task.Result)
            {
                if (sm != null)
                {
                    sm.Seek(0, SeekOrigin.Begin);
                    var len = (int)sm.Length;
                    var inputByts = new byte[len];
                    sm.Read(inputByts, 0, len);
                    sm.Close();
                    content = Encoding.UTF8.GetString(inputByts);
                }
            }
            
            var pars = $@"error：\r\n id = {guid};\r\n sessionId = {session.SessionID};\r\n 
                url = {request.RawUrl};\r\n contentType = {request.ContentType};\r\n 
            content = {content};   keys={keys}";

            return pars;
        }
    }
}